package com.example.java_second_hand_market;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class OrderAdminDialog extends Stage {

    BorderPane bp;
    String DBUrl=ParameterDB.ParaDBUserUrl;
    String DBUser="root", DBPassword="123456";
    private final int ROWS_PER_PAGE = 10;
    @FXML
    private TableView<CompleteItem> tableView = new TableView<>();
    @FXML
    private Pagination pagination;
    private ObservableList<CompleteItem> data=FXCollections.observableArrayList();

    @FXML
    private Button sendback=new Button("退款");
    @FXML
    private Button del=new Button("删除");

    private Button edit=new Button("修改价格");
    User user;
    CompleteItem cit;
    public OrderAdminDialog(User us,int width,int height){
        user=us;
        data = getInitialData();

        // 配置TableView
        setupTableView();

        // 创建分页控件
        pagination = new Pagination((data.size() + ROWS_PER_PAGE - 1) / ROWS_PER_PAGE);
        pagination.setPageFactory(this::createPage);

        VBox vbox = new VBox(tableView, pagination);
        HBox hb=new HBox();
        hb.getChildren().addAll(sendback,del,edit);
        hb.setAlignment(Pos.CENTER);

        bp=new BorderPane();
        bp.setBottom(hb);
        bp.setCenter(vbox);

        Scene scene=new Scene(bp);
        this.setScene(scene);


        sendback.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                sendaction();
            }
        });
        del.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                delaction();
            }
        });
        edit.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                priceedit();
            }
        });
        setTitle("订单管理");

    }
    public ObservableList<CompleteItem> getInitialData() {
        try{
            Connection con= DriverManager.getConnection(DBUrl,DBUser,DBPassword);
            Statement stmt=con.createStatement();
            if(user.getClass().getName()=="com.example.java_second_hand_market.Seller") {
                System.out.println("1");
                ResultSet rs1 = stmt.executeQuery("SELECT * FROM item_list WHERE seller = '" + user.getName() + "'");
                while (rs1.next()) {
                    data.add(new CompleteItem(new Item(rs1.getString("name"), rs1.getString("price"), rs1.getString("seller"),rs1.getInt("id")),rs1.getString("buyer")));
                }
                if (con != null) {
                    try {
                        rs1.close();
                        stmt.close();
                        con.close();

                    } catch (SQLException err) {
                        System.out.println("1121212333");
                    }
                }
            }else {
                if (user.getClass().getName()=="com.example.java_second_hand_market.Admin"){
                    ResultSet rs1 = stmt.executeQuery("SELECT * FROM item_list ");
                    while (rs1.next()) {
                        data.add(new CompleteItem(new Item(rs1.getString("name"), rs1.getString("price"), rs1.getString("seller"),rs1.getInt("id")),rs1.getString("buyer")));
                    }
                    if (con != null) {
                        try {
                            rs1.close();
                            stmt.close();
                            con.close();

                        } catch (SQLException err) {
                            System.out.println("133333");
                        }
                    }
                }
            }
        }catch (SQLException e){
            System.out.println("暂无该用户数据");
        }

        return data;
    }
    private void setupTableView() {
        // "姓名"列
        TableColumn<CompleteItem, String> nameColumn = new TableColumn<>("姓名");
        nameColumn.setCellValueFactory(cellData -> {
            return new SimpleStringProperty(cellData.getValue().getIt().getName());
        });

        // "价格"列
        TableColumn<CompleteItem, String> priceColumn = new TableColumn<>("价格");
        priceColumn.setCellValueFactory(cellData -> {
            return new SimpleStringProperty(cellData.getValue().getIt().getPrice());
        });

        // "商家"列，使用自定义的CellValueFactory来访问seller的name
        TableColumn<CompleteItem, String> sellerColumn = new TableColumn<>("商家");
        sellerColumn.setCellValueFactory(cellData -> {
            Item item = cellData.getValue().getIt();
            return new SimpleStringProperty(item.getSeller().getName());
        });

        // "买家"列
        TableColumn<CompleteItem, String> buyerColumn = new TableColumn<>("买家");
        buyerColumn.setCellValueFactory(cellData -> cellData.getValue().buyerProperty());

        // 将列添加到TableView
        tableView.getColumns().addAll(nameColumn, priceColumn, sellerColumn, buyerColumn);
    }
    private class CompleteItem{
        Item it;
        private final SimpleStringProperty buyer;

        public CompleteItem(Item it, String buyer) {
            this.it = it;
            this.buyer=new SimpleStringProperty(buyer);
        }

        public String getBuyer() {
            return buyer.get();
        }

        public void setBuyer(String buyer) {
            this.buyer.set(buyer);  // 设置 buyer 字段
        }

        public SimpleStringProperty buyerProperty() {
            return buyer;  // 返回 buyer 的 Property
        }

        public Item getIt() {
            return it;
        }

        public void setIt(Item it) {
            this.it = it;
        }
    }
    private VBox createPage(int pageIndex) {
        int fromIndex = pageIndex * ROWS_PER_PAGE;
        int toIndex = Math.min(fromIndex + ROWS_PER_PAGE, data.size());

        List<CompleteItem> pageItems = data.subList(fromIndex, toIndex);
        ObservableList<CompleteItem> pageData = FXCollections.observableArrayList(pageItems);
        tableView.setItems(pageData);

        return new VBox(tableView);
    }

    public void sendaction() {
        cit = tableView.getSelectionModel().getSelectedItem();
        try {
            Connection con = DriverManager.getConnection(DBUrl, DBUser, DBPassword);
            Statement stmt = con.createStatement();
            stmt.executeUpdate("UPDATE item_list set is_sold =0, buyer = NULL where id = '" + cit.getIt().getInfoId() + "';");
            if (con != null) {
                try {
                    stmt.close();
                    con.close();
                } catch (SQLException e) {
                    System.out.println("13131");
                }
            }
        } catch (SQLException e) {
            CommonDialog.WarningDialog("警告");
        }
        data.clear();
        data = getInitialData();

        // 配置TableView


        // 创建分页控件
        pagination .setPageCount((data.size() + ROWS_PER_PAGE - 1) / ROWS_PER_PAGE);
        pagination.setPageFactory(this::createPage);

        tableView.setItems(data); // 直接设置TableView的数据源
        tableView.refresh();
        VBox vbox = new VBox(tableView, pagination);
        HBox hb=new HBox();
        hb.getChildren().addAll(sendback,del,edit);
        hb.setAlignment(Pos.CENTER);


        bp.setBottom(hb);
        bp.setCenter(vbox);


    }
    public void delaction(){
        cit = tableView.getSelectionModel().getSelectedItem();
        try {
            Connection con = DriverManager.getConnection(DBUrl, DBUser, DBPassword);
            Statement stmt = con.createStatement();
            stmt.executeUpdate("DELETE FROM item_list where id = '"+cit.getIt().getInfoId()+"';");
            if (con != null) {
                try {
                    stmt.close();
                    con.close();
                } catch (SQLException e) {
                    System.out.println("15345");
                }
            }
        } catch (SQLException e) {
            CommonDialog.WarningDialog("警告");
        }
        data.clear();
        data = getInitialData();

        // 配置TableView


        // 创建分页控件
        pagination .setPageCount((data.size() + ROWS_PER_PAGE - 1) / ROWS_PER_PAGE);
        pagination.setPageFactory(this::createPage);

        tableView.setItems(data); // 直接设置TableView的数据源
        tableView.refresh();
        VBox vbox = new VBox(tableView, pagination);
        HBox hb=new HBox();
        hb.getChildren().addAll(sendback,del,edit);
        hb.setAlignment(Pos.CENTER);


        bp.setBottom(hb);
        bp.setCenter(vbox);

    }
    public  void refresh(){
        data.clear();
        data = getInitialData();

        // 配置TableView


        // 创建分页控件
        pagination .setPageCount((data.size() + ROWS_PER_PAGE - 1) / ROWS_PER_PAGE);
        pagination.setPageFactory(this::createPage);

        tableView.setItems(data); // 直接设置TableView的数据源
        tableView.refresh();
        VBox vbox = new VBox(tableView, pagination);
        HBox hb=new HBox();
        hb.getChildren().addAll(sendback,del,edit);
        hb.setAlignment(Pos.CENTER);


        bp.setBottom(hb);
        bp.setCenter(vbox);
    }
    public void priceedit(){
        TextInputDialog tid=new TextInputDialog("请输入新价格");
        cit=tableView.getSelectionModel().getSelectedItem();
        tid.setHeaderText("修改价格");
        tid.setContentText("输入价格");
        Optional<String> result=tid.showAndWait();
        result.ifPresent(np->{
            try {
                Connection con = DriverManager.getConnection(DBUrl, DBUser, DBPassword);
                Statement stmt = con.createStatement();
                stmt.executeUpdate("UPDATE item_list set price = '"+np+"'where id ="+cit.getIt().getInfoId()+";");
                if (con != null) {
                    try {
                        stmt.close();
                        con.close();
                    } catch (SQLException e) {
                        System.out.println("1534599");
                    }
                }
            } catch (SQLException e) {
                CommonDialog.WarningDialog("警告");
            }
            CommonDialog.InformationDialog("修改成功");
        });


        data.clear();
        data = getInitialData();

        // 配置TableView


        // 创建分页控件
        pagination .setPageCount((data.size() + ROWS_PER_PAGE - 1) / ROWS_PER_PAGE);
        pagination.setPageFactory(this::createPage);

        tableView.setItems(data); // 直接设置TableView的数据源
        tableView.refresh();
        VBox vbox = new VBox(tableView, pagination);
        HBox hb=new HBox();
        hb.getChildren().addAll(sendback,del,edit);
        hb.setAlignment(Pos.CENTER);


        bp.setBottom(hb);
        bp.setCenter(vbox);


    }


    public BorderPane getBp(){
        return  bp;
    }
}
